package pers.lx.crm.service.info.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.lx.crm.base.common.pigeon.Result;
import pers.lx.crm.base.constant.ErrorConstant;
import pers.lx.crm.base.constant.KeyConstants;
import pers.lx.crm.base.util.ResultUtil;
import pers.lx.crm.dao.info.TagBlockDao;
import pers.lx.crm.entiy.info.TagBlockDO;
import pers.lx.crm.entiy.info.TagDO;
import pers.lx.crm.service.info.TagBlockService;

import java.util.List;

/**
 * Created by lx on 2017/3/4.
 */
@Service
public class TagBlockServiceImpl implements TagBlockService {

    @Autowired
    private TagBlockDao tagBlockDao ;

    @Override
    public Result getTagBlocks(TagBlockDO tagBlockDO) {
        Result result = new Result() ;
        try {
            tagBlockDO.setList(tagBlockDao.selectTagBlockListPage(tagBlockDO));
            return ResultUtil.getPageResult(tagBlockDO,result) ;
        } catch (Exception e){
            e.printStackTrace();
            result.setError(ErrorConstant.UNKNOWN_ERROR);
        }
        return result;
    }

    @Transactional
    @Override
    public Result addTagBlock(TagBlockDO tagBlockDO) {
        Result result = new Result() ;
        tagBlockDao.insertTagBlock(tagBlockDO);
        for (TagDO tagDO:tagBlockDO.getTags()){
            tagBlockDao.insertTagLabels(tagBlockDO.getId(),tagDO.getId());
        }
        return result;
    }

    @Transactional
    @Override
    public Result updateTagBlock(TagBlockDO tagBlockDO) {
        Result result = new Result() ;
        tagBlockDao.updateTagBlock(tagBlockDO);
        tagBlockDao.deleteTagLabels(tagBlockDO.getId());
        for (TagDO tagDO:tagBlockDO.getTags()){
            tagBlockDao.insertTagLabels(tagBlockDO.getId(),tagDO.getId());
        }
        return result;
    }

    @Transactional
    @Override
    public Result removeTagBlocks(List<TagBlockDO> tagBlockDOs) {
        Result result = new Result() ;
        for (TagBlockDO tagBlockDO:tagBlockDOs){
            tagBlockDao.deleteTagLabels(tagBlockDO.getId());
            tagBlockDao.deleteTagBlock(tagBlockDO.getId());
        }
        return result;
    }

    @Override
    public Result getTags(TagBlockDO tagBlockDO) {
        Result result = new Result() ;
        result.addParam(KeyConstants.LIST_KEY,tagBlockDao.selectTagList(tagBlockDO.getId()));
        return result;
    }
}
